import api from './config'
import { getFallbackURL } from '@/config/api-config'
import logger from '../utils/logger.js'

/**
 * 获取作业列表
 * @param {Object} params - 查询参数（页码、页大小、筛选条件等）
 * @returns {Promise} API响应
 */
export const getHomeworkList = async (params = {}) => {
  try {
    logger.log('📚 [API] 获取作业列表...');
    logger.log('📋 [API] 查询参数:', params);
    logger.log('🌐 [API] 请求地址: /api/goc/homework/list');
    logger.log('📊 [API] 请求方法: GET');
    
    const response = await api.get('/goc/homework/list', {
      params: params
    });
    
    logger.log('✅ [API] 作业列表获取成功');
    logger.log('📄 [API] 完整响应:', response);
    logger.log('📊 [API] 响应状态码:', response?.status);
    logger.log('📦 [API] 响应数据:', response?.data);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 获取作业列表失败:', error);
    throw error;
  }
}

/**
 * 创建新作业
 * @param {Object} homeworkData - 作业数据
 * @returns {Promise} API响应
 */
export const createHomework = async (homeworkData) => {
  try {
    logger.log('➕ [API] 创建新作业...');
    logger.log('📋 [API] 作业数据:', homeworkData);
    logger.log('🌐 [API] 请求地址: /api/goc/homework/create');
    logger.log('📊 [API] 请求方法: POST');
    
    const response = await api.post('/goc/homework/create', homeworkData);
    
    logger.log('✅ [API] 作业创建成功');
    logger.log('📄 [API] 完整响应:', response);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 创建作业失败:', error);
    throw error;
  }
}

/**
 * 更新作业
 * @param {string} homeworkId - 作业ID
 * @param {Object} homeworkData - 作业数据
 * @returns {Promise} API响应
 */
export const updateHomework = async (homeworkId, homeworkData) => {
  try {
    logger.log('✏️ [API] 更新作业...');
    logger.log('🆔 [API] 作业ID:', homeworkId);
    logger.log('📋 [API] 作业数据:', homeworkData);
    logger.log('🌐 [API] 请求地址: /api/goc/homework/update');
    logger.log('📊 [API] 请求方法: PUT');
    
    const response = await api.put('/goc/homework/update', {
      id: homeworkId,
      ...homeworkData
    });
    
    logger.log('✅ [API] 作业更新成功');
    logger.log('📄 [API] 完整响应:', response);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 更新作业失败:', error);
    throw error;
  }
}

/**
 * 删除作业
 * @param {string} homeworkId - 作业ID
 * @returns {Promise} API响应
 */
export const deleteHomework = async (homeworkId) => {
  try {
    logger.log('🗑️ [API] 删除作业...');
    logger.log('🆔 [API] 作业ID:', homeworkId);
    logger.log('🌐 [API] 请求地址: /api/goc/homework/delete');
    logger.log('📊 [API] 请求方法: DELETE');
    
      // 构建完整URL用于调试
  const baseURL = getFallbackURL(api);
  const fullURL = `${baseURL}/goc/homework/delete?id=${homeworkId}`;
    logger.log('🌐 [API] 完整删除URL:', fullURL);
    
    const response = await api.delete('/goc/homework/delete', {
      params: { id: homeworkId }
    });
    
    logger.log('✅ [API] 作业删除成功');
    logger.log('📄 [API] 完整响应:', response);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 删除作业失败:', error);
    throw error;
  }
}

/**
 * 获取作业详情
 * @param {string} homeworkId - 作业ID
 * @returns {Promise} API响应
 */
export const getHomeworkDetail = async (homeworkId) => {
  try {
    logger.log('🔍 [API] 获取作业详情...');
    logger.log('🆔 [API] 作业ID:', homeworkId);
    logger.log('🌐 [API] 请求地址: /api/goc/homework/detail');
    logger.log('📊 [API] 请求方法: GET');
    
    const response = await api.get('/goc/homework/detail', {
      params: { id: homeworkId }
    });
    
    logger.log('✅ [API] 作业详情获取成功');
    logger.log('📄 [API] 完整响应:', response);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 获取作业详情失败:', error);
    throw error;
  }
}

/**
 * 获取作业成绩排名
 * @param {string} homeworkId - 作业ID
 * @returns {Promise} API响应
 */
export const getHomeworkRanking = async (homeworkId) => {
  try {
    logger.log('🏆 [API] 获取作业成绩排名...');
    logger.log('🆔 [API] 作业ID:', homeworkId);
    logger.log('🌐 [API] 请求地址: /api/goc/homework/ranking');
    logger.log('📊 [API] 请求方法: GET');
    
    const response = await api.get('/goc/homework/ranking', {
      params: { id: homeworkId }
    });
    
    logger.log('✅ [API] 作业成绩排名获取成功');
    logger.log('📄 [API] 完整响应:', response);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 获取作业成绩排名失败:', error);
    throw error;
  }
}

/**
 * 获取作业排名
 * @param {string} homeworkId - 作业ID
 * @returns {Promise} API响应
 */
export const getHomeworkRank = async (homeworkId) => {
  try {
    logger.log('🏆 [API] 获取作业排名...');
    logger.log('🆔 [API] 作业ID:', homeworkId);
    logger.log('🌐 [API] 请求地址: /api/goc/homework/rank');
    logger.log('📊 [API] 请求方法: GET');
    logger.log('🔗 [API] 完整URL: /api/goc/homework/rank?homeworkId=' + homeworkId);
    
    const response = await api.get('/goc/homework/rank', {
      params: {
        homeworkId: homeworkId
      }
    });
    
    logger.log('✅ [API] 作业排名获取成功');
    logger.log('📄 [API] 完整响应:', response);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 获取作业排名失败:', error);
    throw error;
  }
}

/**
 * 发布作业
 * @param {string} homeworkId - 作业ID
 * @returns {Promise} API响应
 */
export const publishHomework = async (homeworkId) => {
  try {
    logger.log('📢 [API] 发布作业...');
    logger.log('🆔 [API] 作业ID:', homeworkId);
    logger.log('🌐 [API] 请求地址: /api/goc/homework/publish');
    logger.log('📊 [API] 请求方法: PUT');
    logger.log('🔗 [API] 完整URL: /api/goc/homework/publish?id=' + homeworkId);
    
    const response = await api.put('/goc/homework/publish', null, {
      params: {
        id: homeworkId
      }
    });
    
    logger.log('✅ [API] 作业发布成功');
    logger.log('📄 [API] 完整响应:', response);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 发布作业失败:', error);
    throw error;
  }
}

/**
 * 复制作业（发布作业到班级）
 * @param {Object} copyData - 复制作业数据
 * @param {string} copyData.sourceHomeworkId - 被发布的作业id
 * @param {string} copyData.targetTeamId - 接收这个作业的班级id（必须为字符串，避免大整数精度丢失）
 * @param {string} copyData.newTitle - 作业的新名字
 * @returns {Promise} API响应
 */
export const copyHomework = async (copyData) => {
  try {
    logger.log('📤 [API] 复制作业（发布到班级）...');
    logger.log('📋 [API] 复制数据:', copyData);
    logger.log('📋 [API] targetTeamId类型:', typeof copyData.targetTeamId);
    logger.log('📋 [API] targetTeamId值:', copyData.targetTeamId);
    logger.log('🌐 [API] 请求地址: /goc/homework/copy');
    logger.log('📊 [API] 请求方法: POST');
    
    // 确保targetTeamId是字符串类型，避免大整数精度丢失
    const requestData = {
      ...copyData,
      targetTeamId: String(copyData.targetTeamId)
    };
    
    logger.log('📦 [API] 处理后的请求数据:', requestData);
    logger.log('📦 [API] targetTeamId最终类型:', typeof requestData.targetTeamId);
    logger.log('📦 [API] targetTeamId最终值:', requestData.targetTeamId);
    
    const response = await api.post('/goc/homework/copy', requestData);
    
    logger.log('✅ [API] 作业复制成功');
    logger.log('📄 [API] 完整响应:', response);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 复制作业失败:', error);
    throw error;
  }
} 

/**
 * 获取我创建的题目列表
 * @param {Object} params - 查询参数（页码、页大小、筛选条件等）
 * @returns {Promise} API响应
 */
export const getMyCreatQuestion = async (params = {}) => {
  try {
    logger.log('📚 [API] 获取我创建的题目列表...');
    logger.log('📋 [API] 查询参数:', params);
    logger.log('🌐 [API] 请求地址: /api/goc/homework/myCreatQuestion');
    logger.log('📊 [API] 请求方法: GET');
    logger.log('🔑 [API] 将令牌放到请求头中');
    
    // 构建完整URL用于调试
    const baseURL = getFallbackURL(api);
    const fullURL = `${baseURL}/goc/homework/myCreatQuestion`;
    logger.log('🌐 [API] 完整URL:', fullURL);
    logger.log('🌐 [API] 实际目标地址: https://3f283f47.r9.cpolar.cn/goc/homework/myCreatQuestion');
    
    const response = await api.get('/goc/homework/myCreatQuestion', {
      params: params
    });
    
    logger.log('✅ [API] 我创建的题目列表获取成功');
    logger.log('📄 [API] 完整响应:', response);
    logger.log('📊 [API] 响应状态码:', response?.status);
    logger.log('📦 [API] 响应数据:', response?.data);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 获取我创建的题目列表失败:', error);
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method,
      headers: error.config?.headers
    });
    throw error;
  }
}

/**
 * 获取我创建的作业列表
 * @param {Object} params - 查询参数（页码、页大小、筛选条件等）
 * @returns {Promise} API响应
 */
export const getMyCreatHomework = async (params = {}) => {
  try {
    logger.log('📚 [API] 获取我创建的作业列表...');
    logger.log('📋 [API] 查询参数:', params);
    logger.log('🌐 [API] 请求地址: /goc/homework/myCreatHomework');
    logger.log('📊 [API] 请求方法: GET');
    logger.log('🔑 [API] 将令牌放到请求头中');
    
    // 获取 JWT 令牌
    const token = localStorage.getItem('token');
    logger.log('🔑 [API] JWT令牌状态:', token ? '已获取' : '未找到');
    
    const response = await api.get('/goc/homework/myCreatHomework', {
      params: params,
      headers: {
        'Authorization': token || ''
      }
    });
    
    logger.log('✅ [API] 我创建的作业列表获取成功');
    logger.log('📄 [API] 完整响应:', response);
    logger.log('📊 [API] 响应状态码:', response?.status);
    logger.log('📦 [API] 响应数据:', response?.data);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 获取我创建的作业列表失败:', error);
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method,
      headers: error.config?.headers
    });
    throw error;
  }
}

/**
 * 根据团队ID查询班级作业
 * @param {string} teamId - 班级ID（团队ID）
 * @param {number} page - 页码（可选）
 * @param {number} size - 每页数量（可选）
 * @returns {Promise} API响应
 */
export const getHomeworkByTeamId = async (teamId, page = 1, size = 10) => {
  try {
    logger.log('🔍 [API] 根据团队ID查询班级作业...');
    logger.log('🆔 [API] 团队ID:', teamId);
    logger.log('🆔 [API] 团队ID类型:', typeof teamId);
    logger.log('📄 [API] 分页参数: page =', page, ', size =', size);
    logger.log('🌐 [API] 请求地址: /goc/homework/class');
    logger.log('📊 [API] 请求方法: GET');
    
    // 确保teamId是字符串类型，避免大整数精度丢失
    const teamIdStr = String(teamId);
    logger.log('📦 [API] 处理后的团队ID:', teamIdStr);
    
    const response = await api.get('/goc/homework/class', {
      params: {
        teamId: teamIdStr,
        page: parseInt(page),
        size: parseInt(size)
      }
    });
    
    logger.log('✅ [API] 班级作业查询成功');
    logger.log('📄 [API] 完整响应:', response);
    logger.log('📊 [API] 响应状态码:', response?.status);
    logger.log('📦 [API] 响应数据:', response?.data);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 查询班级作业失败:', error);
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method,
      headers: error.config?.headers
    });
    throw error;
  }
}

/**
 * 提前结束作业
 * @param {string|number} homeworkId - 作业ID
 * @returns {Promise} API响应
 */
export const earlyEndHomework = async (homeworkId) => {
  try {
    logger.log('⏹️ [API] 提前结束作业...');
    logger.log('🆔 [API] 作业ID:', homeworkId);
    logger.log('🆔 [API] 作业ID类型:', typeof homeworkId);
    logger.log('🌐 [API] 请求地址: /api/goc/homework/early-end');
    logger.log('📊 [API] 请求方法: POST');
    logger.log('🔑 [API] 将令牌放到请求头中');
    
    // 🔥 保持字符串格式，避免大整数精度丢失
    const id = String(homeworkId);
    logger.log('📦 [API] 处理后的作业ID:', id, '类型:', typeof id);
    logger.log('📦 [API] 作业ID长度:', id.length, '位');
    
    const response = await api.post('/goc/homework/early-end', {
      id: id  // body参数，JSON格式
    });
    
    logger.log('✅ [API] 提前结束作业成功');
    logger.log('📄 [API] 完整响应:', response);
    logger.log('📊 [API] 响应状态码:', response?.status);
    logger.log('📦 [API] 响应数据:', response?.data);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 提前结束作业失败:', error);
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    });
    throw error;
  }
}

/**
 * 获取学生作业结果
 * @param {string|number} homeworkId - 作业ID
 * @param {string|number} studentId - 学生ID
 * @returns {Promise} API响应
 */
export const getStudentHomeworkResult = async (homeworkId, studentId) => {
  try {
    logger.log('👨‍🎓 [API] 获取学生作业结果...');
    logger.log('🆔 [API] 作业ID:', homeworkId);
    logger.log('🆔 [API] 学生ID:', studentId);
    logger.log('🌐 [API] 请求地址: /goc/homework/getStudentHomeworkResult');
    logger.log('📊 [API] 请求方法: GET');
    
    const response = await api.get('/goc/homework/getStudentHomeworkResult', {
      params: {
        homeworkId: homeworkId,
        studentId: studentId
      }
    });
    
    logger.log('✅ [API] 学生作业结果获取成功');
    logger.log('📄 [API] 完整响应:', response);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 获取学生作业结果失败:', error);
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    });
    throw error;
  }
}

/**
 * 获取题目的上次提交代码
 * @param {string|number} homeworkId - 作业ID
 * @param {string|number} testQuestionId - 题目ID
 * @returns {Promise} API响应
 */
export const getQuestionCurrentCode = async (homeworkId, testQuestionId) => {
  try {
    logger.log('📝 [API] 获取题目上次提交代码...');
    logger.log('🆔 [API] 作业ID:', homeworkId);
    logger.log('🆔 [API] 题目ID:', testQuestionId);
    logger.log('🌐 [API] 请求地址: /goc/homework/question-current-code');
    logger.log('📊 [API] 请求方法: GET');
    
    const response = await api.get('/goc/homework/question-current-code', {
      params: {
        homeworkId: homeworkId,
        testQuestionId: testQuestionId
      }
    });
    
    logger.log('✅ [API] 题目上次提交代码获取成功');
    logger.log('📄 [API] 完整响应:', response);
    
    return response;
    
  } catch (error) {
    logger.error('❌ [API] 获取题目上次提交代码失败:', error);
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    });
    throw error;
  }
}